// 初始状态
const state = {
  items: [], // 购物车中的商品
  deliveryFee: 3.8, // 配送费
  packagingFee: 5, // 打包费
  redPacketDiscount: 10, // 红包优惠金额
  selectedAddress: {
    location: '',
    name: '',
    phone: ''
  }, // 选择的地址
}

// getters
const getters = {
  cartItems: state => state.items,
  itemCount: state => state.items.length,
  
  // 商品原价总和（不含任何优惠）
  originalTotal: state => {
    return state.items.reduce((total, item) => {
      return total + (item.price * item.quantity);
    }, 0);
  },

  // 商品优惠后总价（仅计算商品折扣）
  itemsDiscountedTotal: state => {
    return state.items.reduce((total, item) => {
      const itemPrice = Math.max(0, (item.price - (item.discount || 0)) * item.quantity);
      return total + itemPrice;
    }, 0);
  },

  // 配送费
  deliveryFee: state => state.deliveryFee,

  // 打包费
  packagingFee: state => state.packagingFee,

  // 红包优惠
  redPacketDiscount: state => state.redPacketDiscount,

  // 最终总价（包含所有费用和优惠）
  totalPrice: (state, getters) => {
    // 商品优惠后总价
    const itemsTotal = getters.itemsDiscountedTotal;
    
    // 加上配送费和打包费
    let total = itemsTotal + state.deliveryFee + state.packagingFee;
    
    // 减去红包优惠
    total = Math.max(0, total - state.redPacketDiscount);
    
    return total;
  },

  // 总优惠金额（包括商品折扣和红包优惠）
  totalDiscount: (state, getters) => {
    // 商品折扣金额
    const itemsDiscount = getters.originalTotal - getters.itemsDiscountedTotal;
    // 加上红包优惠
    return itemsDiscount + state.redPacketDiscount;
  },

  selectedAddress: state => state.selectedAddress
}

// mutations
const mutations = {
  ADD_TO_CART(state, product) {
    console.log('Adding to cart:', product);
    const existingItem = state.items.find(item => item.id === product.id)
    if (existingItem) {
      existingItem.quantity += product.quantity || 1
    } else {
      state.items.push({
        ...product,
        quantity: product.quantity || 1,
        discount: product.discount || 0
      })
    }
    console.log('Cart after adding:', state.items);
  },
  REMOVE_FROM_CART(state, productId) {
    const index = state.items.findIndex(item => item.id === productId)
    if (index > -1) {
      state.items.splice(index, 1)
    }
  },
  UPDATE_QUANTITY(state, { productId, quantity }) {
    const item = state.items.find(item => item.id === productId)
    if (item) {
      item.quantity = quantity
    }
  },
  UPDATE_ITEM_DISCOUNT(state, { productId, discount }) {
    const item = state.items.find(item => item.id === productId)
    if (item) {
      item.discount = discount
    }
  },
  CLEAR_CART(state) {
    state.items = []
  },
  SET_DELIVERY_FEE(state, fee) {
    state.deliveryFee = fee
  },
  SET_PACKAGING_FEE(state, fee) {
    state.packagingFee = fee
  },
  SET_SELECTED_ADDRESS(state, address) {
    state.selectedAddress = address
  }
}

// actions
const actions = {
  addToCart({ commit }, product) {
    console.log('addToCart action called with:', product);
    commit('ADD_TO_CART', product)
  },
  removeFromCart({ commit }, productId) {
    commit('REMOVE_FROM_CART', productId)
  },
  updateQuantity({ commit }, payload) {
    commit('UPDATE_QUANTITY', payload)
  },
  updateItemDiscount({ commit }, payload) {
    commit('UPDATE_ITEM_DISCOUNT', payload)
  },
  clearCart({ commit }) {
    commit('CLEAR_CART')
  },
  setDeliveryFee({ commit }, fee) {
    commit('SET_DELIVERY_FEE', fee)
  },
  setPackagingFee({ commit }, fee) {
    commit('SET_PACKAGING_FEE', fee)
  },
  setSelectedAddress({ commit }, address) {
    commit('SET_SELECTED_ADDRESS', address)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
} 